package com.tianji.learning.mq;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.InteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;

@Slf4j // 使用Lombok注解，自动生成日志对象
@Component // 将该类标记为Spring组件，由Spring容器管理
@RequiredArgsConstructor // Lombok注解，生成包含final字段的构造函数
public class LikeTimesChangeListener {

    // 注入InteractionReplyService，用于处理回答或评论的业务逻辑
    private final InteractionReplyService replyService;

    /**
     * FIXME：监听点赞次数变更消息
     * @param likedTimesDTOs 点赞次数变更的DTO列表
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "qa.liked.times.queue", durable = "true"), // 定义持久化队列
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC), // 使用TOPIC类型交换机
            key = QA_LIKED_TIMES_KEY // 绑定路由键
    ))
    public void listenReplyLikedTimesChange(List<LikedTimesDTO> likedTimesDTOs) {
        // 记录调试日志，表示监听到点赞数变更
        log.debug("监听到回答或评论的点赞数变更");

        // 初始化InteractionReply列表，容量与传入的DTO列表相同
        List<InteractionReply> list = new ArrayList<>(likedTimesDTOs.size());

        // 遍历所有点赞次数变更的DTO
        for (LikedTimesDTO likedTimesDTO : likedTimesDTOs) {
            // 创建InteractionReply对象
            InteractionReply reply = new InteractionReply();
            // 设置业务ID
            reply.setId(likedTimesDTO.getBizId());
            // 设置点赞次数
            reply.setLikedTimes(likedTimesDTO.getLikedTimes());
            // 将对象添加到列表
            list.add(reply);
        }

        // 批量更新数据库中的点赞次数
        replyService.updateBatchById(list);
    }
}
